package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    //注入 FreeMarkerConfigurer 生成 静态页面 ,可以用其生成一个 Configuration 对象
    private FreeMarkerConfigurer freeMarkerConfigurer;

    // 注入 properties 配置文件中定义的 名称为 out_put_path 的变量
    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public Result add(Integer[] checkgroupIds, Setmeal setmeal) {
        try {
            setmealDao.add(setmeal);
            Integer setmealId = setmeal.getId();
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.add_t_setmeal_checkgroup(setmealId, checkgroupId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SETMEAL_SUCCESS);
        }
        //将 存储到数据库中的 文件名 存储到另一个 set集合中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        //调用该方法，生成静态页面
        generateMobilestaticHtml();


        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }
    // 当前方法所需静态页面 的 生成
    // 直接在要 修改页面内容的方法中调用该方法即可
    public void generateMobilestaticHtml(){

        // 数据有错误，到时候要改
        List<Setmeal> setmealList1 = setmealDao.findPage();
        List<Setmeal> setmealList = new ArrayList<>();
        for (Setmeal setmeal1 : setmealList1) {
            Setmeal setmeal = setmealDao.findById(setmeal1.getId());
            setmealList.add(setmeal);
        }

        //套餐列表静态页面
        generateMobilesetmealListHtml(setmealList);

        //套餐详情静态页面
        generateMobilesetmealDetailHtml(setmealList);
    }

    //generateMobilesetmealListHtml
    //套餐列表静态页面
    public void generateMobilesetmealListHtml(List<Setmeal> setmealList){
        Map map = new HashMap();
        map.put("setmealList",setmealList);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    // generateMobilesetmealDetailHtml
    //套餐详情静态页面  setmealList
    public void generateMobilesetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmeal);
            generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    // 通用的 用于生成模板页面的方法
    //要传递 模板名称  生成的 html 的名字 以及数据 ，此时已经配置
    public void generateHtml(String teplateName, String htmlName, Map<String ,Object> map) {
        Writer out = null;
        try {
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            Template template = configuration.getTemplate(teplateName);
            out =new OutputStreamWriter(new FileOutputStream(outPutPath+"/"+htmlName),"utf-8");
            template.process(map,out);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if( out!= null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }




    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        List<Setmeal> list = null;

        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        if (queryPageBean.getQueryString() == null || "".equals(queryPageBean.getQueryString())) {
            list= setmealDao.findPage();
        } else {
            list = setmealDao.findPage1(queryPageBean.getQueryString());
        }


        return new PageResult(new PageInfo(list).getTotal(), list);
    }


    // ---------------用户端-----------------
    @Override
    //查询所有套餐
    public Result getSetmeal(){
        try {
            List<Setmeal> setmealList = setmealDao.getSetmeal();
            return new Result(true,"查询套餐成功",setmealList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询套餐失败");
        }

    }


    @Override
    //查询某一个套餐的详细信息
    public Result findById(Integer id){
        try {
            Setmeal setmeal = setmealDao.findById(id);
            System.out.println(setmeal.getImg());
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

    // 分页查询
    public PageResult getPageSetmeal(Integer start,Integer pageSize){
        PageHelper.startPage(start,pageSize);
        List<Setmeal> setmealList = setmealDao.getSetmeal();
        PageInfo pageInfo = new PageInfo<>(setmealList);
        return new PageResult(pageInfo.getTotal(),setmealList);
    }

    //套餐收入查询
    @Override
    public List<Map<String, Object>> findSetmealIncome(Map<String, String> map) {
        return setmealDao.findSetmealIncome(map);
    }


}
